package org.iartisan.maven.apidoc.plugin;

import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.iartisan.maven.apidoc.config.ApiDocConfig;
import org.iartisan.maven.apidoc.utils.StringUtil;

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * 插件执行入口
 *
 * @author King
 * @version 1.0
 */
@Mojo(name = "go")
public class ExecuteCommand extends AbstractMojo {

    @Parameter
    private ApiDocConfig apiDocConfig;

    @Override
    public void execute() throws MojoExecutionException, MojoFailureException {
        //todo 目前只支持windows
        //String osName = System.getProperty("os.name");
        if (null == apiDocConfig) {
            getLog().error("配置不能为空");
            throw new MojoFailureException("配置不能为空");
        }
        StringBuffer command = new StringBuffer("apidoc");
        command.append(" -i ").append(apiDocConfig.getInput());
        if (StringUtil.isNotEmpty(apiDocConfig.getOutput())) {
            command.append(" -o ").append(apiDocConfig.getOutput());
        }
        if (StringUtil.isNotEmpty(apiDocConfig.getTemplate())) {
            command.append(" -t ").append(apiDocConfig.getTemplate());
        }
        BufferedReader bufferedReader = null;
        try {
            getLog().info("开始执行命令:" + command.toString());
            Process process = Runtime.getRuntime().exec("cmd /c " + command.toString());
            bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                getLog().info(line);
            }
        } catch (Exception e) {
            getLog().error("apiDoc生成异常:", e);
        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (Exception e) {
                    getLog().error(e);
                }
            }
        }
    }

}
